package com.luocj.brvah_srl.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

import com.luocj.brvah_srl.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;

public class StraggActivity extends AppCompatActivity {

    private RecyclerView recyclerview;
    private SmartRefreshLayout smartRefreshLayout;
    private StraggAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stragg);
        initView();
        initData();
    }

    private ArrayList<String> initData() {
        ArrayList<String> datas = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            datas.add(" item :" + i);
        }
        return datas;
    }

    private void initView() {
        smartRefreshLayout = findViewById(R.id.smartrefreshlayout_straggle);
        recyclerview = findViewById(R.id.recyclerview_starggle);
        recyclerview.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        adapter = new StraggAdapter(StraggActivity.this, null);
        recyclerview.setAdapter(adapter);

        smartRefreshLayout.autoRefresh();
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refresh(refreshlayout, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refresh(refreshlayout, true);
            }
        });
    }

    private void refresh(RefreshLayout refreshlayout, final boolean isreFresh) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isreFresh) {
                    adapter.setNewData(initData());
                    smartRefreshLayout.finishRefresh();
                    smartRefreshLayout.setLoadmoreFinished(false);
                } else {
                    adapter.addData(initData());
                    smartRefreshLayout.finishLoadmore();
                }
            }
        }, 2000);
    }
}
